package com.jaks.xpense.adapters;

import java.util.List;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.jaks.xpense.data.entities.TagModel;

public class CheckBoxArrayAdapter extends ArrayAdapter<TagModel> {

	private final List<TagModel> list;
	private final Activity context;
	private final int resource;
	private final int checkBoxResourceId;
	private final int textViewResourceId;

	private static class ViewHolder {
		protected TextView textView;
		protected CheckBox checkBox;
	}

	public CheckBoxArrayAdapter(Activity context, int resource, int textViewResourceId,
	    int checkBoxResourceId, List<TagModel> objects) {
		super(context, resource, checkBoxResourceId, objects);

		this.context = context;
		this.list = objects;
		this.resource = resource;
		this.textViewResourceId = textViewResourceId;
		this.checkBoxResourceId = checkBoxResourceId;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		View view = null;
		if (convertView == null) {
			LayoutInflater inflater = context.getLayoutInflater();
			view = inflater.inflate(resource, null);

			final ViewHolder holder = new ViewHolder();
			holder.textView = (TextView) view.findViewById(textViewResourceId);
			holder.checkBox = (CheckBox) view.findViewById(checkBoxResourceId);
			holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					TagModel element = (TagModel) holder.checkBox.getTag();
					element.setSelected(buttonView.isChecked());
				}
			});

			view.setTag(holder);
			holder.checkBox.setTag(list.get(position));
		} else {
			view = convertView;
			((ViewHolder) view.getTag()).checkBox.setTag(list.get(position));
		}

		ViewHolder viewHolder = (ViewHolder) view.getTag();
		viewHolder.textView.setText(list.get(position).getName());
		viewHolder.checkBox.setChecked(list.get(position).isSelected());

		return view;
	}
}